/**
 \* Created with IntelliJ IDEA.
 \* User: 彭诗杰
 \* Date: 2018/8/6 16:09
 \* Description:  噪声类state
 \*/

import API from '../../api/api_noise'
import util from '../../common/util';

const state = {
  // 当天最新数据
  noiseSystem: {},
  // 最新数据
  noiseLatest: {},
  // 实时数据
  noisePresents: [],
  noisePresentsPaging:[],
  // 历史数据
  noiseHistories: [],
  noisePagination: {
    page: 0,
    limit: 10,
    total: 100,
  },
};

const getters = {
  noiseFactors: state => {
    return state.noiseFactors;
  },
  noiseSystem: state => {
    return state.noiseSystem;
  },
  noiseLatest: state => {
    return state.noiseLatest;
  },
  noisePresents: state => {
    return state.noisePresents;
  },
  noiseHistories: state => {
    return state.noiseHistories;
  },
  noisePresentsPaging:state=>{
    return state.noisePresentsPaging;
  }
};

const actions = {
  /**
   * 不分页获取单指标历史数据
   * @param commit
   * @param state
   * @param params
   * @returns {Promise<any>}
   */
  getNoiseFactorHistoriesNoPagingAct({commit, state}, params) {
    return new Promise((resolve, reject) => {
      API.getNoiseHistoriesNoPaging(params).then(result => {
        //console.log(result);
        resolve(result);
      }, err => {
        reject(err);
      }).catch(error => {
        reject(error);
      })
    })
  },

  /**
   * 按指标获取后台当日实时数据并组装成el-table格式
   *
   * @param commit
   * @param state
   * @param params
   * @returns {Promise<any>}
   */
  getNoisePresentPagingAct({commit, state}, params) {
    return new Promise(async (resolve, reject) => {
      let solidHistories = [];
      let total = 0;
      try {
        if (params.factors) {
          for (let factor of params.factors) {
            let factorParams = {
              solidId: params.solidId,
              systemCode: params.systemCode,
              factorCode: factor.code,
              dateStart: params.dateStart,
              dateEnd: params.dateEnd,
              page: params.pagination.page,
              limit: params.pagination.limit
            };
            let factorHistories = await API.getNoiseHistoryValues(factorParams);
            //console.log(factorHistories);
            let formatFactorHistories = factorHistories.factorValueVos;
            //console.log(formatFactorHistories);
            total = factorHistories.total;
            //console.log(total);
            formatFactorHistories.forEach(formatFactorHistory => {
              solidHistories.push(formatFactorHistory);
            });
          }
        }
      } catch (err) {
        reject(err)
      }
      let groupedByTime = util.groupArray(solidHistories, 'time');
      console.log('groupedByTime', groupedByTime)
      // 将按时间戳分好的数据按factorId进行赋值
      let allRows = [];
      groupedByTime.forEach(groupedTimeItem => {
        let eachRow = [];
        eachRow.time = groupedTimeItem.initial;
        eachRow.data = [];
        params.factors.forEach(factor => {
          groupedTimeItem.list.forEach(item => {
            if (factor.id === item.factorId) {
              let eachRowItem = {
                id: item.id,
                name: factor.code,
                value: item.value,
                outRange: item.outRange
              };
              eachRow.data.push(eachRowItem);
            }
          })
        });
        allRows.push(eachRow);
        //console.log(allRows)
      });

      let pagination = {
        total: total,
        page: params.pagination.page,
        limit: params.pagination.limit,
      };
      commit('setNoisePresentsPaging', allRows);
      resolve(pagination);
    })
  },

  /**
   * 按指标获取后台历史数据并组装成el-table格式，草特么的难写
   * @param commit
   * @param state
   * @param params
   * @returns {Promise}
   */
  getNoiseHistoryListAct({commit, state}, params) {
    return new Promise(async (resolve, reject) => {
      let airHistories = [];
      let total = 0;
      try {
        if (params.factors) {
          for (let factor of params.factors) {
            let factorParams = {
              solidId: params.solidId,
              systemCode: params.systemCode,
              factorCode: factor.code,
              dateStart: params.dateStart,
              dateEnd: params.dateEnd,
              page: params.pagination.page,
              limit: params.pagination.limit
            };
            let factorHistories = await API.getNoiseHistoryValues(factorParams);
            //console.log(factorHistories);
            let formatFactorHistories = factorHistories.factorValueVos;
            total = factorHistories.total;
            formatFactorHistories.forEach(formatFactorHistory => {
              airHistories.push(formatFactorHistory);
            });
          }
        }
      } catch (err) {
        reject(err)
      }
      let groupedByTime = util.groupArray(airHistories, 'time');
      //commit('setSewageHistoriesWithRange', groupedByTime);
      //console.log(groupedByTime);
      // 将按时间戳分好的数据按factorId进行赋值
      let allRows = [];
      groupedByTime.forEach(groupedTimeItem => {
        let eachRow = [];
        eachRow.time = groupedTimeItem.initial;
        eachRow.data = [];
        params.factors.forEach(factor => {
          groupedTimeItem.list.forEach(item => {
            if (factor.id === item.factorId) {
              let eachRowItem = {
                id: item.id,
                name: factor.code,
                value: item.value,
                outRange: item.outRange
              };
              eachRow.data.push(eachRowItem);
            }
          })
        });
        allRows.push(eachRow);
      });
      let pagination = {
        total: total,
        page: params.pagination.page,
        limit: params.pagination.limit,
      };
      //console.log({file:"noise.js", function:"getNoiseHistoryListAct", result:allRows});
      commit('setNoiseHistoryList', allRows);
      resolve(pagination);
    });
  },


  /**
   * 从服务器获取当前服务区噪声监测集成商系统
   * @param commit
   * @param state
   * @param area
   * @returns {Promise<any>}
   */
  getNoiseSystemsAct({commit, state}, area) {
    return new Promise((resolve, reject) => {
      API.getNoiseSystems(area.noiseId).then(systems => {
        resolve(systems);
      }, error => {
        reject(error)
      }).catch(err => {
        reject(err)
      })
    })
  },

  /**
   * 从服务器获取噪声监测指标
   * @param commit
   * @param state
   * @param params  {noiseId,systemCode}
   */
  getNoiseFactorsAct({commit, state}, params) {
    return new Promise((resolve, reject) => {
      API.getNoiseFactors(params).then(factPageVo => {
        resolve(factPageVo);
      }, error => {
        reject(error)
      }).catch(err => {
        reject(err)
      })
    })
  },

  /**
   * 从服务器获取监测指标最新值
   * @param commit
   * @param state
   * @param params {noiseId, systemCode, factorCode}
   * @returns {Promise}
   */
  getNoiseFactorLatestValueAct({commit, state}, params) {
    return new Promise((resolve, reject) => {
      API.getNoiseLatestValue(params).then(factorValue => {
        resolve(factorValue)
      }, error => {
        reject(error)
      }).catch(err => {
        reject(err)
      })
    })
  },

  setNoisePresentList({commit, state}, data) {
    commit('setNoisePresentList', data)
  },
  setNoiseHistoryList({commit, state}, data) {
    commit('setNoiseHistoryList', data)
  },
  setNoisePagination({commit, state}, data) {
    commit('setNoisePagination', data)
  },
  setNoiseFactorsAct({commit, state}, data) {
    commit('setNoiseFactors', data);
  },
  setNoiseSystemAct({commit, state}, data) {
    commit('setNoiseSystem', data)
  },
  setNoisePresentsPaging({commit, state}, data){
    commit('setNoisePresentsPaging', data);
  }

};

const mutations = {
  setNoiseSystem(state, entity) {
    state.noiseSystem = entity
  },
  setNoisePresentList(state, entity) {
    state.noisePresents = entity;
  },
  setNoiseHistoryList(state, entity) {
    state.noiseHistories = entity;
  },
  setNoisePagination(state, entity) {
    state.noisePagination = entity
  },
  setNoiseLatest(state, entity) {
    state.noiseLatest = entity;
  },
  setNoiseFactors(state, entity) {
    state.noiseFactors = entity;
  },

  setNoisePresentsPaging(state, entity){
    state.noisePresentsPaging = entity;
  }
};

export default {
  state,
  getters,
  actions,
  mutations
}
